<?php

$db = new PGSQLConnector('u_superuser');

if(isset($_POST['register'])) {
    $firstname = $_POST['fname'];
    $lastname = $_POST['lname'];
    $email = $_POST['email'];
    $phone = $_POST['mphone'];
    $sex = $_POST['sex'];
    
    //Creating username
    list($u1,$r) = @str_split($firstname,3);
    list($u2,$r) = @str_split($lastname,3);
    //$username = strtolower($u1 . $u2);
    $username = 'teis';
    //Check if username exist
    $username = checkUniqUsername($username);
    echo $username;
    
    //Create person
    $createPersonSQL = "INSERT INTO person (countrycode,email,firstname,lastname,sex,timecreated)\n";
    $createPersonSQL .= "VALUES ('no','$email','$firstname','$lastname','$sex',now())";
    //Get personid
    $getPersonIDSQL = "SELECT idperson FROM person WHERE lastname = '$firstname' AND email = '$email'";
    //Create user
    $createUserSQL = "INSERT INTO uname (username,idperson,timestart,timeend,timecreated)\n";
    $createUserSQL .= "VALUES ('$username','-1',now(),date('now') + interval '1 year',now())";
    //Set usergroup
    $set2groupSQL = "INSERT INTO uname_ugroup (username,usergroup)\n";
    $set2groupSQL .= "VALUES ('$username','Applicant')";
    //Create query array
    $queries = Array();
    $queries[] = $createPersonSQL;
    $queries[] = $createUserSQL;
    $queries[] = $set2groupSQL;
    //$db->transaction($queries);
    
    //Get idperson and update user
    //$idperson = $db->queryUnique($getPersonIDSQL);
    $updateuserSQL = "UPDATE uname SET idperson = '" . $idperson['idperson'] . "'\n";
    $updateuserSQL .= "WHERE username = '" . $username . "'";
    //$db->query($updateuserSQL);
    
    //Creating password
    //setPassword($username, $phone, $sms);
}

$template = newPage('register');
$template->title = 'Register - IAESTE Application System';
$template->l = $l;

try {
    echo $template->execute();
} catch(Exception $e) {
    echo $e;
}
?>
